<template>
  <div>
    <HeaderComponents/>
    <br>
    <section class="recommend-section">
      <div class="title-bar">
        <h2>为你推荐</h2>
        <a href="#" @click="refreshRecommendations">换一批</a>
      </div>
      <div v-for="content in recommendedContents" :key="content.ctid" class="card" @click="jumpToContentDetail(content.ctid)">
        <div class="card-cover" :style="{ backgroundImage: `url(${content.cover})` }"></div>
        <div class="card-content">
          {{ content.title }}<br>
          {{ content.summary }}
        </div>
      </div>

      <!-- 引入加载更多组件 -->
      <LoadMoreButton
          :is-loading="isLoadingMore"
          :has-more="hasMore"
          :show-no-more="recommendedContents.length > 0"
          button-text="加载更多同类型内容"
          @load-more="loadMore"
      />

      <!-- 没有更多内容提示 -->
      <div v-if="!hasMore && recommendedContents.length > 0" class="no-more">
        没有更多内容了
      </div>

      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </section>
  </div>
</template>

<script>
import axios from 'axios';
// 导入组件
import LoadMoreButton from '../../components/LoadMoreButton.vue';
// 导入 SearchInput 组件
import SearchInput from '../../components/SearchInput.vue';
import HeaderComponents from "@/components/HeaderComponents.vue";

export default {
  components: {
    HeaderComponents,
    LoadMoreButton, // 注册组件
    SearchInput
  },
  data() {
    return {
      user: null,
      recommendedContents: [],
      currentPage: 1,
      hasMore: true,
      isLoadingMore: false,
      errorMessage: '',
      isContentLoaded: false // 新增标志位，用于判断内容是否已经加载过
    };
  },
  created() {
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      this.user = JSON.parse(storedUser);
    } else if (this.$route.query.user) {
      this.user = JSON.parse(this.$route.query.user);
      localStorage.setItem('user', JSON.stringify(this.user));
    }

    const storedPage = localStorage.getItem('currentPage');
    const storedContents = localStorage.getItem('recommendedContents');
    const storedHasMore = localStorage.getItem('hasMore');

    if (storedPage && storedContents && storedHasMore) {
      this.currentPage = parseInt(storedPage);
      this.recommendedContents = JSON.parse(storedContents);
      this.hasMore = JSON.parse(storedHasMore);
    } else {
      this.getRecommendations();
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    jumpToContentDetail(ctid) {
      console.log('查看内容:', ctid);
      this.$router.push({
        path: '/content',
        query: { ctid }
      });
    },
    handleSearch(keyword) {
      this.$router.push({
        name: 'SearchView',
        query: { keyword }
      });
    },
    getRecommendations() {
      if (!this.user || !this.user.uid || this.isLoadingMore) return;

      this.isLoadingMore = true;
      this.errorMessage = '';

      axios.get(`/api/pushPost/recommend/${this.user.uid}`, {
        params: {
          page: this.currentPage
        }
      })
          .then(response => {
            if (response.data.code === 200) {
              const newContents = response.data.data || [];

              if (newContents.length === 0) {
                this.hasMore = false;
              } else {
                // 如果是第一页，替换内容；否则追加
                if (this.currentPage === 1) {
                  this.recommendedContents = newContents;
                } else {
                  this.recommendedContents = [...this.recommendedContents, ...newContents];
                }

                // 检查是否还有更多内容
                this.hasMore = newContents.length >= 5; // 假设每页5条
              }
              // 更新 localStorage
              localStorage.setItem('currentPage', this.currentPage);
              localStorage.setItem('recommendedContents', JSON.stringify(this.recommendedContents));
              localStorage.setItem('hasMore', JSON.stringify(this.hasMore));

            } else {
              this.errorMessage = '获取推荐内容失败: ' + response.data.message;
            }
          })
          .catch(error => {
            this.errorMessage = '请求出错: ' + error.message;
          })
          .finally(() => {
            this.isLoadingMore = false;
          });
    },
    loadMore() {
      if (this.hasMore && !this.isLoadingMore) {
        this.currentPage++;
        this.getRecommendations();
      }
    },

    refreshRecommendations() {
      if (this.isLoadingMore) return;

      this.currentPage = 1;
      this.hasMore = true;
      this.getRecommendations();
    },
    // 添加退出登录方法
    logout() {
      console.log('logout 方法被调用');
      try {
        // 清除本地存储的用户信息
        localStorage.removeItem('user');
        // 清除页面状态信息
        localStorage.removeItem('currentPage');
        localStorage.removeItem('recommendedContents');
        localStorage.removeItem('hasMore');

        console.log('点击退出');
        // 跳转到登录页面
        this.$router.push('login');
      } catch (error) {
        console.error('退出登录时出现错误:', error);
      }
    }
  }
};
</script>

<style src="../../assets/HomePage.css"></style>
